package yz.com.javautil.monitor;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

/**
 * @author Administrator
 */
public class FileMonitorUtil {
    public static FileAlterationMonitor addMonitor(String path) {
        // 监控器
        FileAlterationMonitor monitor = new FileAlterationMonitor(100);
        // 对某个路径的观察者
        FileAlterationObserver observer = new FileAlterationObserver(path);
        // 添加监听事件响应，与path无关，rsync同步需要
        observer.addListener(new PushFileAlterationListener(path));
        // 将观察者添加到监控器
        monitor.addObserver(observer);
        try {
            //启动
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 便于停止
        return monitor;
    }

    public static void main(String[] args) {
        String path = "D:\\home\\JnotifyTest";
        FileAlterationMonitor monitor = FileMonitorUtil.addMonitor(path);
        try {
            //如果不加休眠和停止操作，monitor将会一直监听
            Thread.sleep(10000);
            monitor.stop();//停止监控
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
